本文档介绍如何使用 Cloudflare Tunnel (cloudflared) 将内网服务安全地暴露到公网。
📋 前提条件
- 已在服务器上安装
cloudflared 工具
- 拥有 Cloudflare 账号
- 域名已托管在 Cloudflare
🔐 步骤一:获取授权证书
1. 在服务器上执行登录命令
1
| cloudflared tunnel login
|
命令会输出一个 URL,例如:
1
| https://dash.cloudflare.com/argotunnel?aud=&callback=https://login.cloudflareaccess.org/...
|
2. 在本地浏览器中完成授权
- 复制上述 URL,在本地电脑的浏览器中打开
- 登录你的 Cloudflare 账号
- 选择要使用的域名
- 点击 Authorize 授权
3. 上传证书文件到服务器
由于服务器通常没有图形界面,授权完成后 cert.pem 会下载到你本地电脑,需要手动上传到服务器:
1
| scp -i your-key.pem ~/Downloads/cert.pem user@server:~/.cloudflared/cert.pem
|
🚇 步骤二:创建隧道
1
| cloudflared tunnel create <隧道名称>
|
示例:
1
| cloudflared tunnel create bluebell-tunnel
|
执行成功后会显示:
1 2
| Tunnel credentials written to /root/.cloudflared/<tunnel-id>.json Created tunnel bluebell-tunnel with id <tunnel-id>
|
请记录下隧道 ID,后续配置需要使用。
⚙️ 步骤三:创建配置文件
创建配置文件 ~/.cloudflared/config.yml:
1 2 3 4 5 6 7
| tunnel: <你的隧道ID> credentials-file: /root/.cloudflared/<你的隧道ID>.json
ingress: - hostname: your-domain.com service: http://localhost:80 - service: http_status:404
|
常见配置示例
HTTP 服务 (端口 80)
1 2 3 4
| ingress: - hostname: example.com service: http://localhost:80 - service: http_status:404
|
HTTPS 服务 (端口 443,跳过证书验证)
1 2 3 4 5 6
| ingress: - hostname: example.com service: https://localhost:443 originRequest: noTLSVerify: true - service: http_status:404
|
多域名配置
1 2 3 4 5 6
| ingress: - hostname: app.example.com service: http://localhost:3000 - hostname: api.example.com service: http://localhost:8080 - service: http_status:404
|
🌐 步骤四:配置 DNS 路由
将域名指向隧道:
1
| cloudflared tunnel route dns <隧道名称> <域名>
|
示例:
1
| cloudflared tunnel route dns bluebell-tunnel bluebell.dpdns.org
|
如果域名已有 DNS 记录,使用 --overwrite-dns 覆盖:
1
| cloudflared tunnel route dns --overwrite-dns bluebell-tunnel bluebell.dpdns.org
|
🚀 步骤五:启动隧道
前台运行(调试用)
1
| cloudflared tunnel run <隧道名称>
|
后台运行
1
| nohup cloudflared tunnel run <隧道名称> > /var/log/cloudflared.log 2>&1 &
|
安装为系统服务(推荐)
1 2 3
| cloudflared service install systemctl enable cloudflared systemctl start cloudflared
|
🔍 常用管理命令
1 2 3 4 5 6 7 8 9 10 11
| cloudflared tunnel list
cloudflared tunnel info <隧道名称>
cloudflared tunnel delete <隧道名称>
tail -f /var/log/cloudflared.log
|
❗ 常见问题排查
问题 1:502 Bad Gateway
原因:本地服务未启动或端口不正确
解决方法:
1 2 3 4
| ss -tlnp | grep <端口号>
|
问题 2:connection refused
原因:cloudflared 无法连接到本地服务
检查:
- 确认本地服务正在运行
- 检查防火墙是否放行
- 确认
config.yml 中的端口与实际服务端口一致
问题 3:DNS 记录已存在
错误信息:An A, AAAA, or CNAME record with that host already exists
解决方法:
1
| cloudflared tunnel route dns --overwrite-dns <隧道名称> <域名>
|